﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using ComicIsland.App.CIHelper;
using ComicIsland.App.Resources;
using ComicIsland.Common;
using ComicIsland.Common.Entities.InterfaceJson;
using ComicIsland.Common.Entities.LocalJson;
using ComicIsland.Common.WebHelper;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using SurfaceAd.SDK.WP;

namespace ComicIsland.App.Views
{
    /// <summary>
    /// 漫画社区
    /// </summary>
    public partial class CommunityPage : PhoneApplicationPage
    {
        public CommunityPage()
        {
            InitializeComponent();
            this.surfaceAdCommunity.InitAdControl(AdModeType.Debug);
            LoadCommunity();
            LoadBookcase();
        }

        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            base.OnBackKeyPress(e);
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            base.OnNavigatedFrom(e);
        }
        private void LoadCommunity()
        {
            this.psbStatus.OpenStatusBar(AppResources.DataNoMore);
            string requestUrl = string.Concat(KEYS.REQUEST_HOST, "/comic/getcommunity", "?", KEYS.REQUEST_QUERY_PLATFORM);
            LogHelper.LogInfo(requestUrl, this.GetType(), MethodBase.GetCurrentMethod());
            //
            string cacheDataKey = string.Concat(KEYS.CacheJsonPrefix, MD5.GetMd5String(requestUrl));
            LocalCacheDataHelper cacheHelper = new LocalCacheDataHelper();
            cacheHelper.GetDataFromLocalCache(cacheDataKey);
            if (!cacheHelper.IsReload)
            {
                var rootCharacterString = JSONHelper.Deserialize<JsonComicCommunity>(cacheHelper.LocalCacheData);
                if (!(rootCharacterString != null && rootCharacterString.Info != null && rootCharacterString.Info != null && rootCharacterString.Info.Count > 0))
                {
                    MessageToastManager.Show("返回结果为空！", MessageToastLevel.Error);
                }
                else
                {
                    this.Dispatcher.BeginInvoke(() =>
                    {
                        this.lst.ItemsSource = rootCharacterString.Info;
                    });
                }
                this.psbStatus.CloseStatusBar();
                return;
            }

            WebTaskHelper webTask = new WebTaskHelper(new Uri(requestUrl));
            IAsyncResult ia = webTask.BeginWebTask(delegate(IAsyncResult callBackResult)
            {
                this.Dispatcher.BeginInvoke(() =>
                {
                    try
                    {
                        #region 获取结果处理
                        string result = webTask.EndWebTask(callBackResult);

                        if (string.IsNullOrWhiteSpace(result))
                        {
                            LogHelper.LogError("Result is empty.");
                            return;
                        }
                        //
                        if (result.StartsWith("exception:"))
                        {
                            LogHelper.LogError(result);
                            MessageToastManager.Show("网络连接失败！", MessageToastLevel.Error);
                            return;
                        }
                        LogHelper.LogInfo(result, this.GetType(), MethodBase.GetCurrentMethod());
                        //
                        var rootCharacterString = JSONHelper.Deserialize<JsonComicCommunity>(result);
                        if (!(rootCharacterString != null && rootCharacterString.Info != null && rootCharacterString.Info != null && rootCharacterString.Info.Count > 0))
                        {
                            MessageToastManager.Show("返回结果为空！", MessageToastLevel.Error);
                        }
                        else
                        {
                            this.Dispatcher.BeginInvoke(() =>
                            {
                                cacheHelper.SetDataToLocalCache(cacheDataKey, result);
                                this.lst.ItemsSource = rootCharacterString.Info;
                            });
                        }
                        #endregion 获取结果处理
                    }
                    catch (Exception err)
                    {

                    }
                    finally
                    {
                        this.psbStatus.CloseStatusBar();
                    }
                });
            }, webTask);
        }

        private void appBarPersonal_Click(object sender, EventArgs e)
        {
            NaviService.Navigate(ComicIslandPage.PersonalCenterPage);
        }

        private void lstGrid_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            //var item = ((sender as Grid).DataContext as JsonComicCommunityInfo);
            //if (item == null)
            //    return;
            //if (item.Id == 1)
            //    NaviService.Navigate(ComicIslandPage.CommunityDiscussionPage, string.Concat("?communityId=", item.Id));
            //else if (item.Id == 2)
            //    NaviService.Navigate(ComicIslandPage.CommunityReviewPage, string.Concat("?communityId=", item.Id));
        }

        private void Border_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            var item = ((sender as Border).DataContext as JsonComicCommunityInfo);
            if (item == null)
                return;
            if (item.Id == 1)
                NaviService.Navigate(ComicIslandPage.CommunityDiscussionPage, string.Concat("?communityId=", item.Id));
            else if (item.Id == 2)
                NaviService.Navigate(ComicIslandPage.CommunityReviewPage, string.Concat("?communityId=", item.Id));
        }

        void LoadBookcase()
        {
            LocalBookcaseInfoHelper helper = new LocalBookcaseInfoHelper();
            var itemsources = helper.GetAll(new List<LocalBookcaseStatus>() { LocalBookcaseStatus.Add, LocalBookcaseStatus.Update });
            if (!(itemsources != null && itemsources.Count > 0))
            {
                return;
            }
            List<string> comicIds = new List<string>();
            foreach (var item in itemsources)
            {
                if (item == null)
                    continue;
                if (item.ComicId <= 0)
                    continue;
                comicIds.Add(string.Concat("\"", item.ComicId, "\""));
            }
            string bigBookIds = string.Join(",", comicIds);
            //
            this.psbStatus.OpenStatusBar(AppResources.DataLoading);
            string requestUrl = string.Concat(KEYS.REQUEST_HOST, "/comic/bookrackdiscuss", "?", KEYS.REQUEST_QUERY_PLATFORM);
            LogHelper.LogInfo(requestUrl, this.GetType(), MethodBase.GetCurrentMethod());
            Dictionary<string, object> parameters = new Dictionary<string, object>();
            parameters.Add("\"bigBookids\"", string.Format("[{0}]", bigBookIds));

            PostClientHelper proxy = new PostClientHelper(parameters, PostFormat.JsonJoin);
            string cacheDataKey = string.Concat(KEYS.CacheJsonPrefix, MD5.GetMd5String(string.Concat(requestUrl, proxy.PostData.ToString())));
            LocalCacheDataHelper cacheHelper = new LocalCacheDataHelper();
            cacheHelper.GetDataFromLocalCache(cacheDataKey);
            if (!cacheHelper.IsReload)
            {
                var rootCharacterString = JSONHelper.Deserialize<JsonComicBookRackDiscuss>(cacheHelper.LocalCacheData);
                if (!(rootCharacterString != null && rootCharacterString.Info != null && rootCharacterString.Info != null))
                {
                    //MessageToastManager.Show("返回结果为空！", MessageToastLevel.Error);
                }
                else
                {
                    this.BindBookcase(rootCharacterString.Info);
                }
                this.psbStatus.CloseStatusBar();
                return;
            }

            proxy.DownloadStringCompleted += (sender, e) =>
            {
                this.Dispatcher.BeginInvoke(() =>
               {
                   try
                   {
                       if (e.Error != null)
                       {
                           LogHelper.LogError(e.Error.ToString(), this.GetType(), MethodBase.GetCurrentMethod());
                           return;
                       }

                       #region 获取结果处理
                       string result = e.Result;
                       //LogHelper.LogInfo("JsonComicDetailRelationRecomm:", this.GetType(), MethodBase.GetCurrentMethod());
                       //LogHelper.LogInfo(result, this.GetType(), MethodBase.GetCurrentMethod());

                       if (string.IsNullOrWhiteSpace(result))
                       {
                           LogHelper.LogError("Result is empty.");
                           //MessageToastManager.Show("未获取到数据！", MessageToastLevel.Error);
                           return;
                       }
                       //
                       if (result.StartsWith("exception:"))
                       {
                           LogHelper.LogError(result);
                           //MessageToastManager.Show("网络连接失败！", MessageToastLevel.Error);
                           return;
                       }
                       LogHelper.LogInfo(result, this.GetType(), MethodBase.GetCurrentMethod());

                       //
                       var rootCharacterString = JSONHelper.Deserialize<JsonComicBookRackDiscuss>(result);
                       if (!(rootCharacterString != null && rootCharacterString.Info != null && rootCharacterString.Info != null))
                       {
                           //MessageToastManager.Show("返回结果为空！", MessageToastLevel.Error);
                       }
                       else
                       {
                           cacheHelper.SetDataToLocalCache(cacheDataKey, result);
                           this.BindBookcase(rootCharacterString.Info);
                       }
                       #endregion 获取结果处理
                   }
                   catch (Exception err)
                   {
                   }
                   finally
                   {
                       this.psbStatus.CloseStatusBar();
                   }
               });
            };
            proxy.DownloadStringAsync(new Uri(requestUrl, UriKind.Absolute));
        }


        void BindBookcase(ObservableCollection<JsonComicBookRackDiscussInfo> items)
        {
            if (items != null && items.Count > 0)
            {
                this.llsBookcase.ItemsSource = items;
            }
        }

        /// <summary>
        /// 我书架的书
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void llsGridBookcaseHasCache_Tab(object sender, System.Windows.Input.GestureEventArgs e)
        {
            var item = (sender as Grid).DataContext as JsonComicBookRackDiscussInfo;
            if (item != null)
            {
                NaviService.Navigate(ComicIslandPage.ComicDiscussionPage, string.Concat("?comicId=", item.Id, "&title=", Uri.EscapeDataString(item.Name)));
            }
        }
    }
}